﻿using System.Drawing;
using System.Windows.Forms;

namespace SharpCmd.Windows.Forms.Progress
{
    internal class ProgressBarWithText : ProgressBar
    {
        private StringFormat fmtBlack;
        private StringFormat fmtWhite;

        public ProgressBarWithText()
        {
            this.SetStyle(ControlStyles.UserPaint, true);
            fmtBlack = new StringFormat();
            fmtBlack.Alignment = StringAlignment.Center;
            fmtWhite = new StringFormat();
            fmtWhite.FormatFlags = StringFormatFlags.NoWrap;
            fmtWhite.Trimming = StringTrimming.None;
        }

        public float ProgressFloat
        {
            get
            {
                return (float)Value / (float)Maximum;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            float barRight = ProgressFloat * (float)Width;
            string percentString = ProgressFloat.ToString("0.0%");
            float stringWidth = e.Graphics.MeasureString(percentString, this.Font).Width;
            e.Graphics.DrawString(percentString, this.Font, Brushes.Black, new RectangleF(0, 0, this.Width, this.Height), fmtBlack);
            e.Graphics.FillRectangle(SystemBrushes.Highlight, 0, 0, barRight, this.Height);
            float startX = (this.Width - stringWidth) / 2;
            float rectWidth = barRight - startX;
            e.Graphics.DrawString(percentString, this.Font, Brushes.White, new RectangleF(startX, 0, rectWidth, this.Height), fmtWhite);
        }
    }
}